package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.detailService;
import com.hmall.order.service.logisticsService;
import com.hmall.order.utils.UserHolder;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private UserClient userClient;

    @Autowired
    private detailService detailService;

    @Autowired
    private logisticsService logisticsService;


    /**
     * 创建订单
     *
     * @param params
     * @return
     */
    @Override
    public Long createOrder(RequestParams params) {
        Order order = new Order();
        //根据id查询商品信息
        Item item = itemClient.getById(String.valueOf(params.getItemId()));
        //计算商品总价
        long totalFee = params.getNum() * item.getPrice();
        order.setTotalFee(totalFee);
        order.setPaymentType(params.getPaymentType());
        order.setUserId(UserHolder.getUser());
        //设置status初始值为未支付
        order.setStatus(1);
        //将order写入数据库中
        this.save(order);

        //将orderId信息封装为OrderDetail对象
        OrderDetail detail = new OrderDetail();
        detail.setName(item.getName());
        detail.setSpec(item.getSpec());
        detail.setPrice(item.getPrice());
        detail.setNum(params.getNum());
        detail.setItemId(item.getId());
        detail.setImage(item.getImage());
        detail.setOrderId(order.getId());
        detailService.save(detail);

        //根据地址id查询地址信息
        Address address = userClient.findAddressById(params.getAddressId());

        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address, orderLogistics);
        orderLogistics.setOrderId(order.getId());
        logisticsService.save(orderLogistics);

        //库存扣减
        try {
            itemClient.updateStock(params.getItemId(),params.getNum());
        }catch (Exception E){
            throw new RuntimeException("库存不足！");
        }



        return order.getId();
    }
}
